package demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class JDBCDemo {

	private String className = "com.mysql.jdbc.Driver";
	private String url = "jdbc:mysql://localhost:3306/icommunity?useUnicode=true&characterEncoding=utf-8";
	private String password = "surekam";
	private String username = "root";
	private Connection conn = null;

	public Connection getConn() throws ClassNotFoundException, SQLException {
		if (conn != null)
			return conn;
		Class.forName(className);
		conn = DriverManager.getConnection(url, username, password);
		return conn;
	}

	public void close() throws SQLException {
		conn.close();
	}

	public void testJdbc() throws ClassNotFoundException, SQLException {
		String sql = "select * from tb_ic_article";
		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet result = ps.executeQuery();
		ResultSetMetaData metaData = result.getMetaData();
		int count = metaData.getColumnCount();
		System.out.println("行数：" + count);
		for (int i = 0; i < count; i++) {
//			String catalogName = metaData.getCatalogName(i + 1);
//			System.out.println(catalogName);
			String columnClassName = metaData.getColumnClassName(i+1);
			String columnName = metaData.getColumnName(i+1);
			String columnLabel = metaData.getColumnLabel(i+1);
			
			System.out.println(columnClassName + "\t" + columnName + "\t" + columnLabel);
		}
	}

	public static void main(String[] args) {
		JDBCDemo j = new JDBCDemo();
		try {
			j.getConn();
			j.testJdbc();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				j.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}
}
